package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.util.PackageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //前端明文密码进行MD5加密处理
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        //        //密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工,保存到数据库
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        System.out.println("当前线程id"+Thread.currentThread().getId());
        Employee employee=new Employee();

        //一个个set很麻烦
        //employee.setId(employeeDTO.getId());
        //前拷贝到后面（属性名字需要一致）
        BeanUtils.copyProperties(employeeDTO,employee);

//        employee.setCreateTime(LocalDateTime.now());

        employee.setStatus(1);//StatusConstant.ENABLE;

        //默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        employee.setUpdateTime(LocalDateTime.now());
//
//        //设置当前记录人和修改人的id
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insertEmployee(employee);
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    //用pagehelper简化分页代码的
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1. 获取查询参数
        String name = employeePageQueryDTO.getName();

        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page= employeeMapper.pageSearch(employeePageQueryDTO);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());

//
//        // 2. 计算分页偏移量
//        int offset = (page - 1) * pageSize;
//
//        // 3. 查询当前页数据
//        List<Employee> records = employeeMapper.pageSearch(name, offset, pageSize);
//
//        // 4. 查询总记录数
//        Long total = employeeMapper.count(name);
//
//

        return pageResult;
    }

    /**
     * 启用禁用账号
     * @param status
     * @param id
     */
    @Override
    public void startOrstop(String status, String id) {
//        Employee employee=new Employee();
//        employee.setId(Long.parseLong(id));
//        employee.setStatus(Integer.parseInt(status));
//
//        employee.setUpdateUser(BaseContext.getCurrentId());
//        employee.setUpdateTime(LocalDateTime.now());
        Employee employee=Employee.builder()
                .id(Long.parseLong(id))
                .status(Integer.parseInt(status))
//                .updateTime(LocalDateTime.now())
//                .updateUser(BaseContext.getCurrentId())
                .build();

        employeeMapper.update(employee);

       // employeeMapper.changeStatus(Long.parseLong(id) ,Integer.parseInt(status));
    }

    /**
     * 用户信息的修改
     * @param employeeDTO
     */
    @Override
    public void change(EmployeeDTO employeeDTO) {
        Employee employee=new Employee();

        BeanUtils.copyProperties(employeeDTO,employee);
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.update(employee);

    }

    /**
     * 根据ID获得员工信息
     * @param id
     * @return
     */
    @Override
    public Employee get(Long id) {
        Employee employee=employeeMapper.getById(id);
        //账号不存在的时候
        if(employee == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        employee.setPassword("****");
        return employee;
    }

    /**
     * 修改员工密码
     * @param passwordEditDTO
     */
    @Override
    public void changePassword(PasswordEditDTO passwordEditDTO) {
        Employee employee = employeeMapper.getById(passwordEditDTO.getEmpId());

        //账号不存在的时候
        if(employee == null){
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 获取员工数据库中存储的加密密码
        String dbPassword = employee.getPassword();
        // 对前端传入的旧密码进行MD5加密
        String inputPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());

        // 比较加密后的密码是否一致
        if (dbPassword.equals(inputPassword)) {
            // 旧密码正确，更新新密码
            String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
            Employee employee1 = new Employee();
            employee1.setId(passwordEditDTO.getEmpId());
            employee1.setPassword(newPassword);

//            // 设置更新时间和操作人（关键修复点）
//            employee1.setUpdateTime(LocalDateTime.now());
//            employee1.setUpdateUser(BaseContext.getCurrentId());

            employeeMapper.update(employee1);
        }else {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
    }


}
